import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-11-28
 * Time: 13:23
 */
public class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    //通过一个锁对象
    private Object locker = new Object();

    public MyTimer() {
        //创建一个线程负责执行任务
        Thread thread = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    if (queue.isEmpty()) {
                        continue;
                    }
                    MyTimerTask task = queue.peek();
                    if (System.currentTimeMillis() < task.getTime()) {
                        continue;
                    }else {
                        task.toRun();
                        queue.poll();
                    }
                }
            }
        });
        thread.start();
    }

    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask timerTask = new MyTimerTask(runnable,System.currentTimeMillis() + delay);
            queue.offer(timerTask);
        }
    }
}
